# system
import pickle
import StringIO
import logging
import urllib

# appengine
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

# local
import base

# We expect persons is a array of url encoded csv of fields
def DecodePersons(persons):
  ret = []
  for p in persons:
    temp = DecodeCsv(urllib.unquote(p).split(','))
    if temp:
      ret.append(temp)
    else:
      logging.error("Failed to match p:" + urllib.unquote(p));
  return ret

def SetPersonField(p, key, value):
  if key == "name":
    p.name = value
    return True
  if key == "sex":
    p.sex = value
    return True
  if key == "age":
    p.age = value
    return True
  if key == "contact":
    p.contact = value
    return True
  if key == "address":
    p.address = value
    return True
  if key == "unit":
    p.unit = value
    return True
  if key == "other":
    p.other = value
    return True
  if key == "hospital":
    p.hospital = value
    return True
  if key == "section":
    p.section = value
    return True
  if key == "status":
    p.status = value
    return True
  if key == "hospital_contact":
    p.hospital_contact = value
    return True
  if key == "source":
    p.source = value
    return True
  if key == "shard":
    p.shard = value
    return True
  if key == "pid":
    p.pid = value
    return True
  raise Exception("Unknow key:%s" % key)
  return False

def DecodeCsv(person):
  fields_matched = 0
  p = base.Person()
  for i in xrange(0, len(person), 2): 
    key = person[i]
    value = unicode(person[i + 1], "utf8")
    if SetPersonField(p, key, value):
      fields_matched += 1
  if fields_matched:
    return p
  return None

class LoaderPage(webapp.RequestHandler):
  def post(self):
    encoded_persons = self.request.body.strip().split(' ')
    persons = DecodePersons(encoded_persons)
    logging.error("persons num : %s " % len(persons))
    # May need to look into putting all into the same entity group.
    # otherwise cannot do bulk update
    for p in persons:
      p.put()
